# -*- coding = utf-8 -*-
# @Time    : 2025/4/16 下午5:33
# @Author  : yqk
# @File    : 对称加密.py
# @Software: PyCharm

#pycryptodome
#AES、DES、3DES
# import base64
# from Crypto.Cipher import AES
# #CBC 模式、ECB 模式、CFB 模式、OFB 模式、CTR 模式
# cipher = AES.new(b'1234567890123456', AES.MODE_ECB)
# plaintext = b'1234567890123456'
# ciphertext = cipher.encrypt(plaintext)
# print(ciphertext)
# print(base64.b64encode(ciphertext))
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

def aes_encrypt(key: bytes, iv: bytes, plain_text: str) -> str:
    """
    AES CBC 加密函数

    :param key: 16字节密钥 (bytes)
    :param iv: 16字节初始向量 (bytes)
    :param plain_text: 原始字符串 (str)
    :return: 加密后的Base64字符串 (str)
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plain_text_bytes = plain_text.encode()
    padded_data = pad(plain_text_bytes, AES.block_size)
    encrypted = cipher.encrypt(padded_data)
    return base64.b64encode(encrypted).decode()

def aes_decrypt(key: bytes, iv: bytes, cipher_text_b64: str) -> str:
    """
    AES CBC 解密函数

    :param key: 16字节密钥 (bytes)
    :param iv: 16字节初始向量 (bytes)
    :param cipher_text_b64: Base64 编码的密文 (str)
    :return: 解密后的明文字符串 (str)
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = base64.b64decode(cipher_text_b64)
    decrypted_padded = cipher.decrypt(encrypted)
    return unpad(decrypted_padded, AES.block_size).decode()
key = b'1234567890abcdef'  # 16字节密钥
iv = b'abcdef1234567890'   # 16字节IV
plain_text = "123456"

# 加密
cipher_text = aes_encrypt(key, iv, plain_text)
print("加密后密文：", cipher_text)

# 解密
decrypted = aes_decrypt(key, iv, cipher_text)
print("解密后明文：", decrypted)
